package com.example.arffrecorder.activities;

import Utils.ARFFFileWriter;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.arffrecorder.R;
import com.example.arffrecorder.service.ARFFLocationService;
import com.example.arffrecorder.service.ARFFLocationService.LocalBinder;

public class RecordingActivity extends Activity {

	boolean serviceBound = false;
	ARFFLocationService mService;
	Button startButton, stopButton;
	Intent serviceIntent;
	private String nameOfFile;

	private static final String TAG = RecordingActivity.class.getSimpleName();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_recording);

		startButton = (Button) findViewById(R.id.start_record);
		startButton.setOnClickListener(startSensorReading);
		stopButton = (Button) findViewById(R.id.stop_record);
		stopButton.setOnClickListener(stopSensorReading);
		stopButton.setEnabled(false);
	}

	/**
	 * method for checking if the filename is valid for starting recording
	 * 
	 */
	public boolean isFileNameValid() {
		EditText inputType = (EditText) findViewById(R.id.fileName);
		nameOfFile = inputType.getEditableText().toString();
		if (nameOfFile != null || !nameOfFile.equals(""))
		{
			if (ARFFFileWriter.getInstance().isFileNameValid(nameOfFile)) 
			{
				if (ARFFFileWriter.getInstance().fileExists(
						nameOfFile + getExtension())) {
					System.out.println("File with this name already exists!");
					Toast.makeText(this, "File with this name already exists!",
							Toast.LENGTH_SHORT).show();
					return false;
				} else
					return true;
			} else 
			{
				System.out.println("Invalid filename!");
				Toast.makeText(this, "Invalid filename!", Toast.LENGTH_SHORT)
						.show();
				return false;
			}
		}
		else { 
			//WRONGGGG!!!!!. System.out.println("Unexpected input error!");
			Log.d(TAG, "Unexpected input error.");
			Toast.makeText(this, "Unexpected input error!", Toast.LENGTH_SHORT)
					.show();
			return false;
		}
	}

	/**
	 * Listener for startButton
	 * 
	 */
	View.OnClickListener startSensorReading = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			if (isFileNameValid() && getExtension().length() != 0) {

				ImageView recordImage = (ImageView) findViewById(R.id.recordImage);
				recordImage.setImageResource(R.drawable.record_start);
				stopButton.setEnabled(true);
				startButton.setEnabled(false);
				if (serviceBound == false) {
					serviceIntent.putExtra("fileName", nameOfFile
							+ getExtension());
					bindService(serviceIntent, mConnection,
							Context.BIND_AUTO_CREATE);
					serviceBound = true;
				}
			}
		}
	};

	/**
	 * get file extension from the option chosen by the user from the combobox
	 */
	public String getExtension() {
		Spinner extension = (Spinner) findViewById(R.id.spinner1);
		if (extension != null)
			return extension.getSelectedItem().toString();
		else
			return "";
	}

	/**
	 * Listener for stopButton
	 * 
	 */
	View.OnClickListener stopSensorReading = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			ImageView recordImage = (ImageView) findViewById(R.id.recordImage);
			recordImage.setImageResource(R.drawable.record_stop);
			startButton.setEnabled(true);
			stopButton.setEnabled(false);
			if (serviceBound) {
				unbindService(mConnection);
				serviceBound = false;
			}
		}
	};

	@Override
	protected void onStart() {
		super.onStart();

		// start the service that records data from the accelerometer
		serviceIntent = new Intent(this, ARFFLocationService.class);
		// bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
		// startService(serviceIntent);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.recording, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case R.id.home_page:

			Intent i = new Intent(RecordingActivity.this, MainScreen.class);
			startActivity(i);
			return true;
		case R.id.help:
			Toast.makeText(RecordingActivity.this,
					"Press start button to record data from accelerometer",
					Toast.LENGTH_SHORT).show();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	protected void onResume() {
		super.onResume();
		// mSensorManager.registerListener(this, mAccelerometer,
		// SensorManager.SENSOR_DELAY_FASTEST);
	}

	protected void onPause() {
		super.onPause();
		// mSensorManager.unregisterListener(this);
	}

	@Override
	protected void onStop() {
		super.onStop();
		if (isFinishing() && serviceBound) {
			unbindService(mConnection);
			serviceBound = false;
		}
	}

	// in case orientation changes do not recreate activity (stop service)
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		System.out.println("configChanged");
	}

	private ServiceConnection mConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName className, IBinder service) {
			// We've bound to LocalService, cast the IBinder and get
			// LocalService instance
			LocalBinder binder = (LocalBinder) service;
			mService = binder.getService();
			serviceBound = true;

			EditText fileName = (EditText) findViewById(R.id.fileName);
			// System.out.println("file name: " +
			// fileName.getText().toString());
			// mService.nameFileFromActivity(fileName.getText().toString());

			EditText oxData = (EditText) findViewById(R.id.ox_data);
			oxData.setText(mService.getSensorX() + "");
			// System.out.println(mService.sensorX+"***//**");

			EditText oyData = (EditText) findViewById(R.id.oy_data);
			oyData.setText(mService.getSensorY() + "");

			EditText ozData = (EditText) findViewById(R.id.oz_data);
			ozData.setText(mService.getSensorZ() + "");

		}

		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			serviceBound = false;
		}
	};

	/*
	 * class for receiving broadcast messages containing accelerometer data from
	 * the service
	 */
	private class MyReceiver extends BroadcastReceiver {
		static final String CUSTOM_INTENT = "DATA_CHANGED";

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			Log.d("RecordingActivity: ", "onReceive");
			String measurement = arg1.getStringExtra("measurement");
			System.out.println("I am here");
		}

	}
}
